package org.fenixsoft.jvm.chapter9.my;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JdkDynamicProxyTest {

    public static void main(String[] args) {
        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
        proxyComment1();
        //proxyComment2();
    }

    static void proxyComment1(){
        CommentService service = new CommentServiceImpl();
        Class<? extends CommentService> clazz = service.getClass();
        Object instance = Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object result = method.invoke(service, args);
                System.out.println("add 1 score");
                return result;
            }
        });
        CommentService proxyService = (CommentService) instance;
        proxyService.comment();
    }

    static void proxyComment2(){
        ScoreProxy proxy = new ScoreProxy();
        CommentService proxyService = proxy.bind(new CommentServiceImpl());
        proxyService.comment();
    }

    static class ScoreProxy implements InvocationHandler{
        private CommentService service;

        public CommentService bind(CommentService service){
            this.service = service;
            Class<? extends CommentService> serviceClass = service.getClass();
            return (CommentService) Proxy.newProxyInstance(serviceClass.getClassLoader(), serviceClass.getInterfaces(), this);
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            Object result = method.invoke(service, args);
            System.out.println("add 1 score");
            return result;
        }
    }

}
